<template>
  <div class="product-info-list">
    <Button type="primary" :disabled="disabled" @click="handleClick">订单添加</Button>
    <Button type="primary" :disabled="disabled" @click="handleClickRecord">档案添加</Button>
    <Button type="primary" :disabled="disabled" @click="handleClickManual">手动添加</Button>
    <Button type="primary" :disabled="disabledRemove" @click="handleRemove">删除</Button>
    <table-box ref="tableBox" show-selection show-index no-request :table-height="200" :data="tableData" :table-config="tableConfig" @selection-change="handlerSelectionChange"></table-box>
    <el-dialog :visible.sync="visible" width="70vw" title="产品信息" :close-on-click-modal="false" append-to-body @close="handleClose" @open="handleOpen">
      <table-box ref="tableBox1" v-loading="loading" show-selection no-request :data="tableData1" :table-config="tableConfig1" @selection-change="handlerSelectionChange1"></table-box>
    </el-dialog>
    <el-dialog :visible.sync="visibleProInfo" width="80vw" title="档案添加" :close-on-click-modal="false" append-to-body destroy-on-close @close="handleClose">
      <ProInfo is-relevance @on-relevance="handlerOnRelevance"></ProInfo>
    </el-dialog>
  </div>
</template>
<script>
import { productInfoByPCode, retailDetail } from '@/api/workOrder'
import ProInfo from '@/views/infoData/proInfo'
export default {
  name: 'ProductInfoList',
  components: {
    ProInfo
  },
  props: {
    pCode: {
      type: String,
      default: ''
    },
    ecOrderNumber: {
      type: String,
      default: ''
    },
    buyChannel: {
      type: String,
      default: ''
    },
    orderCode: {
      type: String,
      default: ''
    },
    value: {
      type: Array,
      default: () => []
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      visible: false,
      tableData1: [],
      tableData: [],
      selectionData: [],
      loading: false,
      visibleProInfo: false
    }
  },
  computed: {
    isEbusi() {
      const t = this.orderCode || ''
      return [1, '1'].includes(this.buyChannel) || (!t.includes('LTK') && !t.includes('LSK'))
    },
    tableConfig1() {
      const setting = [
        {
          label: '产品编码',
          prop: 'productCode'
        },
        {
          label: '产品名称',
          prop: 'productName'
        },
        {
          label: '产品型号',
          prop: 'productCategory'
        },
        {
          label: '购买数量',
          prop: 'buyNum'
        }
      ]
      if (this.isEbusi) {
        setting.unshift({
          label: '电商单号',
          prop: 'code'
        })
      }
      return {
        interfacePath: '',
        tableIndex: 1,
        setting
      }
    },

    tableConfig() {
      return {
        interfacePath: '',
        tableIndex: 2,
        setting: [
          {
            label: '产品编码',
            prop: 'productCode',
            render: (h, row) => {
              if (row._type === 'add') {
                return h('el-input', {
                  props: {
                    value: row.productCode,
                    placeholder: '请输入',
                    clearable: true
                  },
                  on: {
                    input: v => {
                      this.$set(row, 'productCode', v)
                    }
                  },
                  nativeOn: {
                    click: e => {
                      e.stopPropagation()
                    }
                  }
                })
              }
              return h('span', row.productCode)
            }
          },
          {
            label: '产品名称',
            prop: 'productName',
            render: (h, row) => {
              if (row._type === 'add') {
                return h('el-input', {
                  props: {
                    value: row.productName,
                    placeholder: '请输入',
                    clearable: true
                  },
                  on: {
                    input: v => {
                      this.$set(row, 'productName', v)
                    }
                  },
                  nativeOn: {
                    click: e => {
                      e.stopPropagation()
                    }
                  }
                })
              }
              return h('span', row.productName)
            }
          },
          {
            label: '产品型号',
            prop: 'productCategory',
            render: (h, row) => {
              if (row._type === 'add') {
                return h('el-input', {
                  props: {
                    value: row.productCategory,
                    placeholder: '请输入',
                    clearable: true
                  },
                  on: {
                    input: v => {
                      this.$set(row, 'productCategory', v)
                    }
                  },
                  nativeOn: {
                    click: e => {
                      e.stopPropagation()
                    }
                  }
                })
              }
              return h('span', row.productCategory)
            }
          },
          {
            label: '处理数量',
            prop: 'handleNum',
            render: (h, row) => {
              row.buyNum = Number.parseInt(row.buyNum)
              row.handleNum = Number.parseInt(row.handleNum)
              const props = {
                size: 'mini',
                min: 1,
                max: row.buyNum,
                value: row.handleNum,
                disabled: this.disabled
              }
              if (isNaN(row.buyNum)) {
                delete props.max
              }
              return h('el-input-number', {
                props,
                key: this.productCode(row),
                on: {
                  change: v => {
                    this.$set(row, 'handleNum', v)
                  }
                },
                nativeOn: {
                  click: e => {
                    e.stopPropagation()
                  }
                }
              })
            }
          }
        ]
      }
    },

    disabledRemove() {
      return this.disabled || this.tableData.length === 0
    }
  },
  watch: {
    value: {
      handler(v) {
        // if (this.visible) {
        this.tableData = [...(v || [])]
        // }
      },
      immediate: true
    },
    tableData: {
      handler() {
        this.refreshTableHeight()
      }
    }
  },
  methods: {
    handleClick() {
      if (this.isEbusi && !this.pCode) {
        this.$message.warning('请输入平台单号!')
        return
      }
      if (!this.isEbusi && !this.orderCode) {
        this.$message.warning('请输入零售订单号!')
        return
      }
      this.tableData1 = []
      this.visible = true
    },
    handleOpen() {
      this.loading = true;
      (this.isEbusi ? productInfoByPCode : retailDetail)(this.isEbusi ? this.pCode : this.orderCode).then(data => {
        const list = []
        if (this.isEbusi) {
          const orderData = (data.data || []).filter(e => ['01', '0'].includes(e.orderType))
          const es = (this.ecOrderNumber || '').split(',').filter(e => e !== '')
          let t = []
          if (es.length === 0) {
            t = orderData
          } else {
            t = orderData.filter(e => es.includes(e.code))
          }
          (t || []).forEach(e => {
            list.push(...(e.productInfos || []))
          })
        } else {
          // if (['01', '0'].includes(data.data.orderType)) {
          list.push(...(data.data.productInfos || []))
          // }
        }
        this.tableData1 = list
        this.$nextTick(() => {
          this.setTableSelection(this.tableData1)
        })
      }).finally(() => {
        this.loading = false
      })
    },
    handleClose() {
      this.$emit('input', [...this.tableData])
    },
    productCode(row) {
      return `${row.productId}`
    },
    handlerSelectionChange1(selectionData) {
      for (const v of selectionData) {
        const productCode = this.productCode(v)
        if (this.tableData.every(e => this.productCode(e) !== productCode)) {
          const buyNum = Number.parseInt(v.buyNum)
          if (!isNaN(buyNum)) {
            v.handleNum = buyNum <= 0 ? 0 : 1
          } else {
            v.handleNum = 0
          }
          this.tableData.push(v)
        }
      }
      // 如果在tableData1中不在selectionData中则删除
      for (let i = 0; i < this.tableData.length; i++) {
        const d = this.tableData[i]
        const productCode = this.productCode(d)
        const exist = this.tableData1.some(e => this.productCode(e) === productCode) && selectionData.every(e => this.productCode(e) !== productCode)
        if (exist) {
          this.tableData.splice(i, 1)
          --i
        }
      }
    },
    handlerSelectionChange(selectionData) {
      this.selectionData = selectionData
    },
    setTableSelection(data) {
      for (const d of data) {
        const productCode = this.productCode(d)
        if (this.tableData.some(e => productCode === this.productCode(e))) {
          this.$nextTick(() => {
            this.$refs.tableBox1.toggleRowSelection(d, true)
          })
        }
      }
    },
    handleRemove() {
      if (!this.singleJudge(this.selectionData, '删除')) {
        return
      }
      for (const v of this.selectionData) {
        const productCode = this.productCode(v)
        const i = this.tableData.findIndex(e => this.productCode(e) === productCode)
        if (i >= 0) {
          this.tableData.splice(i, 1)
        }
      }
      this.$nextTick(() => {
        this.$refs.tableBox.clearSelection()
      })
      this.$emit('input', [...this.tableData])
    },
    // 档案添加
    handleClickRecord() {
      this.visibleProInfo = true
    },
    // 手动添加
    handleClickManual() {
      this.tableData.push({
        productCode: '',
        productName: '',
        productCategory: '',
        handleNum: 1,
        productId: '',
        _type: 'add'
      })
      this.$emit('input', [...this.tableData])
    },
    handlerOnRelevance(selectionData) {
      this.visibleProInfo = false
      for (const d of selectionData) {
        const productCode = this.productCode(d)
        const exist = this.tableData.some(e => this.productCode(e) === productCode)
        if (!exist) {
          this.tableData.push({
            productCode: d.productCode,
            productName: d.productName,
            productCategory: d.productModelCode,
            handleNum: 1,
            productId: d.productId
          })
        }
      }
    },
    refreshTableHeight() {
      this.$nextTick(() => {
        this.$refs.tableBox && this.$refs.tableBox.refreshTableHeight()
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.product-info-list{
  // /deep/ span:first-child{
  //   text-align: left !important;
  // }
  // /deep/ .el-table__empty-block{
  //   & > .el-table__empty-text{
  //     text-align: center !important;
  //   }
  // }
}
</style>
